/*
 * @Author: maskMan
 * @LastEditTime: 2024-03-26 12:22:43
 * @Descripttion:音频管理
 */
import { AudioClip, AudioSource } from 'cc'
import { AUDIO_KEY } from '../define/constants'
import cacheStore from './cacheStore'
function _decorator(target: typeof AudioManager) {
  target._initData()
}
@_decorator
export default class AudioManager {
  private static _musicAudioSource: AudioSource
  /**初始化数据 */
  static _initData() {
    this._musicAudioSource = new AudioSource()
    if (cacheStore.getConfigData(AUDIO_KEY.SOUND) == null) {
      cacheStore.setConfigData(AUDIO_KEY.SOUND, true)
    }
    if (cacheStore.getConfigData(AUDIO_KEY.MUSIC) == null) {
      cacheStore.setConfigData(AUDIO_KEY.MUSIC, true)
    }
  }
  /**
   * @description: 播放音效
   * @param {cc.AudioClip} clip
   * @param {boolean} loop
   * @return {boolean}
   */
  static playSound(clip: AudioClip, loop: boolean = true): boolean {
    const ret = cacheStore.getConfigData(AUDIO_KEY.SOUND)
    if (ret == true) {
      const source = new AudioSource()
      source.clip = clip
      source.play()
      source.loop = loop
      return true
    }
    return false
  }
  /**
   * @description: 播放音乐
   * @param {cc.AudioClip} clip
   * @param {boolean} loop
   * @return {boolean}
   */
  static playMusic(clip: AudioClip, loop: boolean = true): boolean {
    const ret = cacheStore.getConfigData(AUDIO_KEY.MUSIC)
    if (ret == true && this._musicAudioSource.playing == false) {
      const source = this._musicAudioSource
      source.clip = clip
      source.play()
      source.loop = loop
      return true
    }
    return false
  }
  /**
   * @description: 打开音效开关
   * @return {void}
   */
  static openSound() {
    cacheStore.setConfigData(AUDIO_KEY.SOUND, true)
  }
  /**
   * @description: 关闭音效开关
   * @return {void}
   */
  static closeSound() {
    cacheStore.setConfigData(AUDIO_KEY.SOUND, false)
  }
  /**
   * @description: 打开音乐开关
   * @return {void}
   */
  static openMusic() {
    cacheStore.setConfigData(AUDIO_KEY.MUSIC, true)
    if (this._musicAudioSource.clip) {
      this._musicAudioSource.play()
    }
  }
  static closeMusic() {
    if (this._musicAudioSource.clip && this._musicAudioSource.playing) {
      this._musicAudioSource.pause()
    }
    cacheStore.setConfigData(AUDIO_KEY.MUSIC, false)
  }
  /**
   * @description: 打开所有音频开关
   * @return {void}
   */
  static openAll() {
    this.openSound()
    this.openMusic()
  }
  /**
   * @description: 关闭所有音频开关
   * @return {void}
   */
  static closeAll() {
    this.closeSound()
    this.closeMusic()
  }
}
